from flask import current_app, jsonify

from apps.libs.enums import ClientTypeEnum
from apps.libs.redprint import Redprint
from apps.models.user import User
from apps.validators.forms import ClientForm
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

api = Redprint('token')

@api.route('', methods=['POST'])
def get_token():
    form = ClientForm().validate_for_api()
    promise = {
        ClientTypeEnum.USER_EMAIL: User.verify
    }
    identity = promise[ClientTypeEnum(form.type.data)](
        form.account.data,
        form.secret.data
    )
    # Token
    expiration = current_app.config['TOKEN_EXPIRATION']
    token = generate_auth_token(identity['uid'],
                                form.type.data,
                                identity['scope'],
                                expiration)
    t = {
        'token': token.decode('ascii')
    }
    return jsonify(t), 201

def generate_auth_token(uid, ac_type, scope=None, expiration=7200):

    '''生成令牌'''
    s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)

    return s.dumps({
        'uid': uid,
        'type': ac_type.value,
        'scope': scope
    })

# user
# eyJhbGciOiJIUzUxMiIsImlhdCI6MTU0MjcwMDU3MiwiZXhwIjoxNTQ1MjkyNTcyfQ.eyJ1aWQiOjYsInR5cGUiOjEwMCwic2NvcGUiOiJVc2VyU2NvcGUifQ.eHqH5QXLk-dtvcNzpGERiU-gaza__-DsV38YaXPPYDmqO-cHMnHQtPEd4HID57vdQf7Q5GnHjZd4vaeqf6G9kw

# admin
# eyJhbGciOiJIUzUxMiIsImlhdCI6MTU0MjcwMjQwMiwiZXhwIjoxNTQ1Mjk0NDAyfQ.eyJ1aWQiOjcsInR5cGUiOjEwMCwic2NvcGUiOiJBZG1pblNjb3BlIn0.0TGNqVKKG9qp_Nfz9mgnPNP7AeVmYM-iiRH4r3dlfPfEbyj7C6O42fo9gb-fPf3haXwkfTYpdWIF15onI61_eQ